﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using Microsoft.Phone.Controls;
using RapidRepository.TestMobileApplication.Entities;
using RapidRepository.TestMobileApplication.Repositories;
using RapidRepository.TestMobileApplication.View;

namespace RapidRepository.TestMobileApplication
{
    public partial class CustomerSearch : PhoneApplicationPage
    {
        public CustomerSearch()
        {
            InitializeComponent();
        }

        private void SelectCustomer(object sender, RoutedEventArgs e)
        {
            var customerId = (Guid)((System.Windows.FrameworkElement)e.OriginalSource).Tag;
            NavigationService.Navigate(new Uri("/EditCustomer.xaml?id=" + customerId.ToString(), UriKind.Relative));
        }

        private void Search(object sender, RoutedEventArgs e)
        {
            string searchText = SearchText.Text;

            if (!string.IsNullOrEmpty(SearchText.Text))
            {
                SearchCustomers(searchText);
            }
            else
            {
                Customers.ItemsSource = null;
                MessageBox.Show("You must enter at least one character into the search box");
            }
        }

        private void SearchCustomers(string searchText)
        {
            List<CustomerSearchView> customerList = GetCustomers(searchText);
            if (customerList.Count == 0)
            {
                MessageBox.Show("Could not find any customers with the given search criteria, the fields searched on are FirstName, LastName and PostCode");
            }
            else
            {
                Customers.ItemsSource = null;
                SetCustomerListBoxSource(customerList);
            }
        }

        private static List<CustomerSearchView> GetCustomers(string searchText)
        {  
            CustomerRepository repository = new CustomerRepository();

            return repository.Query<CustomerSearchView>().Where(x =>
                x.FirstName.ToLower().Contains(searchText.ToLower()) ||
                x.LastName.ToLower().Contains(searchText.ToLower()) ||
                x.PostCode.ToLower().Contains(searchText.ToLower())).ToList();
        }

        private void SetCustomerListBoxSource(List<CustomerSearchView> customerList)
        {
            if (customerList.Count > 0)
            {
                Customers.ItemsSource = customerList;
            }
            else
            {
                Customers.ItemsSource = null;
            }
        }
    }
}